package com.example.lxj.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.lxj.base.exception.LoginFailedException;
import com.example.lxj.base.utils.JWTUtils;
import com.example.lxj.base.utils.RedisUtils;
import com.example.lxj.system.entity.SysUser;
import com.example.lxj.system.entity.SysUserToken;
import com.example.lxj.system.mapper.SysUserMapper;
import com.example.lxj.system.mapper.SysUserTokenMapper;
import com.example.lxj.system.service.ISysLoginService;
import com.example.lxj.system.service.ISysUserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SysLoginServiceImpl implements ISysLoginService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysUserTokenService sysUserTokenService;

    @Autowired
    private SysUserTokenMapper sysUserTokenMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public String login(SysUser sysUser) {
        // 判断用户是否存在
        SysUser checkUserExist = sysUserMapper.login(sysUser);
        if (ObjectUtil.isNotNull(checkUserExist)) {
            // 判断密码是否正确
            if (sysUser.getPassword().equals(checkUserExist.getPassword())) {
                // 判断用户是否停用
                if("0".equals(checkUserExist.getStatus())){
                    // 生成token
                    SysUserToken userToken = JWTUtils.createToken(checkUserExist);
                    int i = sysUserTokenService.insertOrUpdateSysUserToken(userToken);
                    if(0 < i){
                        return userToken.getUserToken();
                    }else{
                        throw new LoginFailedException("用户名或密码错误");
                    }
                }else{
                    throw new LoginFailedException("用户名或密码错误");
                }
            } else {
                throw new LoginFailedException("用户名或密码错误");
            }
        } else {
            throw new LoginFailedException("用户名或密码错误");
        }
    }


    /**
     * 根据用户token获取用户信息
     * @param userToken 用户token
     * @return
     */
    @Override
    public SysUser getSysUserByUserToken(String userToken) {
        // 根据token获取对应的用户id
        SysUserToken checkUserTokenValid = sysUserTokenService.selectSysUserIdByUserToken(userToken);
        if(ObjectUtil.isNotNull(checkUserTokenValid)){
            return sysUserMapper.selectSysUserByUserId(checkUserTokenValid.getUserId());
        }else{
            throw new RuntimeException("token已过期");
        }
    }

    @Override
    public int exitLogin(Long userId) {
        SysUserToken sysUserToken = new SysUserToken();
        sysUserToken.setUserId(userId);
        sysUserToken.setExpireTime(DateUtil.date());
        // 清空redis
        redisUtils.del(sysUserToken.getUserId().toString());
        return sysUserTokenMapper.updateSysUserToken(sysUserToken);
    }
}
